-- Copyright (c) 2015,2016 Lucky Byte, Inc.
--
-- Summary : 取各种序号功能模块
--
-- Author  : 吴小虎 <xiaohu@lucky-byte.com>
-- Since   : 2016.4.29
--
-- History
--  * 2015.4.29 : 创建此文件
--

-- 获取并更新系统全局跟踪号
--
-- 跟踪号为 6 位数字，不足前补 0
--
local _get_trace_num = function()
    local _t = jdbc.select([[
        update pay_serial set trace_num = trace_num + 1 returning trace_num
    ]])
    local _record = _t.get_record(0)
    local _trace_num = _record.get('trace_num') % 1000000
    return string.pad(tostring(_trace_num), 6, false, '0')
end


-- 获取并更新系统全局批次号
--
-- 批次号为 6 位数字，不足前补 0
--
local _get_batch_num = function()
    local _t = jdbc.select([[
        update pay_serial set batch_num = batch_num + 1 returning batch_num
    ]])
    local _record = _t.get_record(0)
    local _batch_num = _record.get('batch_num') % 1000000
    return string.pad(tostring(_batch_num), 6, false, '0')
end


-- 获取并更新系统全局订单号
--
-- 订单号为 年月日时分秒 + 6 位数字，数字不足 6 位前补 0
--
local _get_order_id = function()
    local _t = jdbc.select([[
        update pay_serial set order_id = order_id + 1 returning order_id
    ]])
    local _record = _t.get_record(0)
    local _order_id = _record.get('order_id') % 1000000
    return os.date('%Y%m%d%H%M%S') .. string.pad(tostring(_order_id), 6, false, '0')
end


core.trace_num = _get_trace_num
core.batch_num = _get_batch_num
core.order_id  = _get_order_id
